#include "SQLiteUtils.h"

#include <QDate>
#include <QDateTime>
#include <QDebug>
#include <QTime>

void SQLiteUtils::executeSqlFile(const QString& fileName, QSqlDatabase& db) {
    // 读取 SQL 文件内容
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "Failed to open SQL file:" << file.errorString();
        return;
    }

    // 读取文件内容并拆分为单独的 SQL 语句
    QTextStream in(&file);
    QString     sqlContent    = in.readAll();
    sqlContent                = sqlContent.replace('\n', ' ');
    QStringList sqlStatements = sqlContent.split(';', QString::SkipEmptyParts);

    // 执行每个 SQL 语句
    QSqlQuery query(db);
    for (const QString& statement : sqlStatements) {
        qDebug() << statement + ';';
        query.prepare(statement);
        if (!query.exec()) {
            qDebug() << "Failed to execute SQL statement:" << query.lastError().text();
        }
        else {
            qDebug() << "Success to execute SQL statement";
        }
    }

    // 关闭文件
    file.close();
}

bool SQLiteUtils::initDatabase() {
    // 检查数据库文件是否存在
    QFile file(DB_PATH);
    if (!file.exists()) {
        // 如果文件不存在，创建数据库
        db = QSqlDatabase::addDatabase("QSQLITE");
        db.setDatabaseName(DB_PATH);

        if (!db.open()) {
            qDebug() << "Failed to create database.";
            return false;
        }

        // 执行sql文件来初始化数据库
        executeSqlFile("database/sql/boost_chat.sql", db);
    }
    else {
        db = QSqlDatabase::addDatabase("QSQLITE", DB_PATH);
        db.setDatabaseName(DB_PATH);
    }

    return true;
}

SQLiteUtils::SQLiteUtils() {
    if (QSqlDatabase::contains(DB_PATH)) {
        db = QSqlDatabase::database(DB_PATH);
    }
    else {
        initDatabase();
    }
    if (!db.open()) {
        qDebug() << "Database connection failed.";
    }
    else {
        qDebug() << "Database connection Success.";
    }
}

SQLiteUtils::~SQLiteUtils() {
    // 关闭数据库连接
    db.close();
}

bool SQLiteUtils::hasAccount(LoginAccount account) {
    QString sql = "select `userId` from login WHERE userId = ?;";

    QSqlQuery query(db);
    query.prepare(sql);
    query.bindValue(0, account.userId);
    if (query.exec()) {
        if (query.next()) {
            return true;
        }
    }
    else {
        // 查询执行失败
        qDebug() << "hasAccount error:" << query.lastError().text();
    }

    return false;
}

bool SQLiteUtils::hasFileInfo(QString fileUrl) {
    if (!db.open()) return false;
    QString sql = "select hashcode,name,url,datetime,type form files where url = ?;";

    QSqlQuery query(db);
    query.prepare(sql);
    query.bindValue(0, fileUrl);

    if (query.exec()) {
        if (query.next()) {
            return true;
        }
    }
    else {
        // 查询执行失败
        qDebug() << "hasFileInfo error:" << query.lastError().text();
        return false;
    }

    return false;
}

bool SQLiteUtils::insertFileInfo(QString fileUrl, QString hashcode) {
    if (!db.open()) return false;

    // 获取当前日期和时间
    QDateTime currentDateTime = QDateTime::currentDateTime();
    // 获取当前时间戳（以秒为单位）
    qint64 timestampInSeconds = currentDateTime.toSecsSinceEpoch();

    QString sql = "INSERT INTO `main`.`files`(`hashcode`, `name`, `url`, `datetime`, `type`) VALUES (?, ?, ?, ?, ?);";

    QSqlQuery query(db);
    query.prepare(sql);
    query.bindValue(0, hashcode);
    query.bindValue(1, fileUrl.mid(fileUrl.lastIndexOf('/') + 1));
    query.bindValue(2, fileUrl);
    query.bindValue(3, timestampInSeconds);
    query.bindValue(4, fileUrl.mid(fileUrl.lastIndexOf('.')));

    if (query.exec()) {
        return true;
    }
    else {
        // 查询执行失败
        qDebug() << "insertFileInfo error:" << query.lastError().text();
        return false;
    }

    return false;
}

bool SQLiteUtils::insertAccount(LoginAccount account) {
    // 获取当前日期和时间
    QDateTime currentDateTime = QDateTime::currentDateTime();
    // 获取当前时间戳（以秒为单位）
    qint64 timestampInSeconds = currentDateTime.toSecsSinceEpoch();

    QString sql = "\
INSERT INTO `main`.`login`\
(`userId`, `account`, `password`, `headshot`, `datatime`) \
VALUES (?, ?, ?, ?, ?)";

    QSqlQuery query(db);
    query.prepare(sql);
    query.bindValue(0, account.userId);
    query.bindValue(1, account.account);
    query.bindValue(2, account.password);
    query.bindValue(3, account.headshot);
    query.bindValue(4, timestampInSeconds);

    if (query.exec()) {
        return true;
    }
    else {
        // 查询执行失败
        qDebug() << "insertAccount error:" << query.lastError().text();
        return false;
    }

    return false;
}

bool SQLiteUtils::updateAccount(LoginAccount account) {
    // 获取当前日期和时间
    QDateTime currentDateTime = QDateTime::currentDateTime();
    // 获取当前时间戳（以秒为单位）
    qint64 timestampInSeconds = currentDateTime.toSecsSinceEpoch();

    QString sql = "\
UPDATE`main`.`login`\
SET `account` = ?, `password` = ?, `headshot` = ?, `datatime` = ? WHERE userId = ?";

    QSqlQuery query(db);
    query.prepare(sql);
    query.bindValue(0, account.account);
    query.bindValue(1, account.password);
    query.bindValue(2, account.headshot);
    query.bindValue(3, timestampInSeconds);
    query.bindValue(4, account.userId);

    if (query.exec()) {
        return true;
    }
    else {
        // 查询执行失败
        qDebug() << "updateAccount error:" << query.lastError().text();
        return false;
    }

    return false;
}

bool SQLiteUtils::deleteAccount(LoginAccount account) {
    QString sql = "DELETE FROM login WHERE userId = ?";

    QSqlQuery query(db);
    query.prepare(sql);
    query.bindValue(0, account.userId);

    if (query.exec()) {
        return true;
    }
    else {
        // 查询执行失败
        qDebug() << "deleteAccount error:" << query.lastError().text();
        return false;
    }

    return false;
}

bool SQLiteUtils::pushAccount(LoginAccount account) {
    if (hasAccount(account)) {
        updateAccount(account);
    }
    else {
        insertAccount(account);
    }
    return true;
}

QList<LoginAccount> SQLiteUtils::getLoginAccounts() {
    if (!db.open()) return {};

    QString sql = "select `userId`, `account`, `password`, `headshot`, `datatime` from login ORDER BY `datatime` DESC;";

    QList<LoginAccount> list;

    QSqlQuery query(db);
    query.prepare(sql);
    if (query.exec()) {
        while (query.next()) {
            LoginAccount account;
            account.userId   = query.value("userId").toString();
            account.account  = query.value("account").toString();
            account.password = query.value("password").toString();
            account.headshot = query.value("headshot").toString();
            account.time     = query.value("datatime").toLongLong();
            list.push_back(account);
        }
    }
    else {
        // 查询执行失败
        qDebug() << "getLoginAccounts error:" << query.lastError().text();
    }

    return list;
}
